package cn.mengfly.testnrz.im.server.handler;

import cn.mengfly.testnrz.im.ProtoMsg;
import cn.mengfly.testnrz.im.server.ServerSession;
import cn.mengfly.testnrz.im.server.cocurrent.CallBackTask;
import cn.mengfly.testnrz.im.server.cocurrent.CallbackTaskScheduler;
import cn.mengfly.testnrz.im.server.processer.LoginProcesser;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author Mengfly
 */
@ChannelHandler.Sharable
public class LoginRequestHandler extends ChannelInboundHandlerAdapter {

    LoginProcesser loginProcesser = new LoginProcesser();

    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }
        final ProtoMsg.Message pkg = ((ProtoMsg.Message) msg);
        ProtoMsg.HeadType type = pkg.getType();
        if (!type.equals(loginProcesser.type())) {
            super.channelRead(ctx, msg);
            return;
        }
        final ServerSession session = new ServerSession(ctx.channel());

        // 异步任务，处理登录的逻辑
        CallbackTaskScheduler.add(new CallBackTask<Boolean>() {

            @Override
            public Boolean execute() throws Exception {
                return loginProcesser.action(session, pkg);
            }

            @Override
            public void onBack(Boolean r) {
                if (r) {
                    ctx.pipeline().remove(LoginRequestHandler.this);
                    System.out.println("登录成功：" + session.getUser());
                } else {
                    ServerSession.closeSession(ctx);
                    System.out.println("登录失败：" + session.getUser());
                }
            }

            @Override
            public void onException(Throwable t) {
                t.printStackTrace();
                ServerSession.closeSession(ctx);
                System.out.println("登录失败：" + session.getUser());
            }
        });
    }
}
